package com.st.rest;

import com.st.common.constant.Constants;
import com.st.common.core.ResultEntity;
import com.st.common.utils.ServletUtils;
import com.st.system.common.other.LoginUser;
import com.st.system.common.other.SysLoginService;
import com.st.system.common.other.SysPermissionService;
import com.st.system.common.other.TokenService;
import com.st.system.domain.SysMenu;
import com.st.system.domain.SysUser;
import com.st.system.domain.model.LoginBody;
import com.st.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author ssw
 * @version 1.0
 * @date 2020/12/3 10:41
 */
@Api(value = "系统登录")
@RestController
@RequiredArgsConstructor
@RequestMapping("/login")
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResultEntity login(@RequestBody LoginBody loginBody)
    {
        ResultEntity ajax = ResultEntity.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("用户信息")
    @GetMapping("getInfo")
    public ResultEntity getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        ResultEntity ajax = ResultEntity.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getMenus")
    public ResultEntity getMenus()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return ResultEntity.success(menuService.buildMenus(menus));
    }
}
